<?php
header('content-type:text/html;charset=utf-8');

function read_all ($dir){
	$split = DIRECTORY_SEPARATOR;
    if(!is_dir($dir)) return false;
    
    $handle = opendir($dir);
    
    if($handle){
        while(($fl = readdir($handle)) !== false){
            $temp = $dir.DIRECTORY_SEPARATOR.$fl;
            $file_name = '';
            
            if(is_dir($temp) && $fl!='.' && $fl != '..'){
               
                  $dir_array = explode($split,$temp);
              
                   read_all($temp);
                
              
            }else{
                if($fl!='.' && $fl != '..'){
                 
                  $file_name = str_replace('inc_deal', 'inc_deal_result',$temp);
                  $file_name_dir = str_replace('inc_deal', 'inc_deal_result',$dir);
                 
                  if(!is_dir($file_name_dir)){
                     $res= mkdir($file_name_dir,0777,true);
                    
                  }

                  // echo $file_name.'<br/>';
                  $content = deal_content($temp);
                header('Content-Type: text/html; charset=utf-8');
                 file_put_contents($file_name,$content);
                 
                  
                }
            }
        }
    
    }
}

/** 
 * js escape php 实现 
 * @param $string the string want to be escaped 
 * @param $in_encoding       
 * @param $out_encoding      
 */ 
function escape($string, $in_encoding = 'UTF-8',$out_encoding = 'UCS-2') { 
    $return = ''; 
    if (function_exists('mb_get_info')) { 
        for($x = 0; $x < mb_strlen ( $string, $in_encoding ); $x ++) { 
            $str = mb_substr ( $string, $x, 1, $in_encoding ); 
            if (strlen ( $str ) > 1) { // 多字节字符 
                $return .= '%u' . strtoupper ( bin2hex ( mb_convert_encoding ( $str, $out_encoding, $in_encoding ) ) ); 
            } else { 
                $return .= '%' . strtoupper ( bin2hex ( $str ) ); 
            } 
        } 
    } 
    return $return; 
}
/*
*解码php unescape
*/
function unescape($str) 
{ 
    $ret = ''; 
    $len = strlen($str); 
    for ($i = 0; $i < $len; $i ++) 
    { 
        if ($str[$i] == '%' && $str[$i + 1] == 'u') 
        { 
            $val = hexdec(substr($str, $i + 2, 4)); 
            if ($val < 0x7f) 
                $ret .= chr($val); 
            else  
                if ($val < 0x800) 
                    $ret .= chr(0xc0 | ($val >> 6)) . 
                     chr(0x80 | ($val & 0x3f)); 
                else 
                    $ret .= chr(0xe0 | ($val >> 12)) . 
                     chr(0x80 | (($val >> 6) & 0x3f)) . 
                     chr(0x80 | ($val & 0x3f)); 
            $i += 5; 
        } else  
            if ($str[$i] == '%') 
            { 
                $ret .= urldecode(substr($str, $i, 3)); 
                $i += 2; 
            } else 
                $ret .= $str[$i]; 
    } 
    return $ret; 
}

function mdbchar($strarray) {
  // var_dump($strarray);
  // exit;
return '\\'.base_convert($strarray[0],16,8);
}
//是否UTF-8
 function isUTF8($str) {
       if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", "UTF-8"), "UTF-8", "UTF-32")) {
            return true;
      } else {
           return false;
       }
}
/*
*读取文件内容并处理
*/
function deal_content($file_path){

  $content =  file_get_contents($file_path);
//   $reg = "/\\\\x.{2}/i";

// $str = preg_replace_callback($reg,"mdbchar",$content);
// return $str;

     //preg_replace_callback()
            //执行一个正则表达式搜索并且使用一个回调进行替换
            $datas = array();
            $noMatchs = array();
            $pattern = '#\\[x0-9][a-z0-9]{2}#i';
  $return_data =  preg_replace_callback($pattern, function ($matches) use ($datas, $noMatchs,$file_path) {
                   // echo $matches[0];
                   // echo '<br/>';
                   // strpos(haystack, needle)
                   // exit;

                    $deal_str = $matches[0];
                    $x_pos = strpos($deal_str, '\x');
                    $xiegang_pos = strpos($deal_str, '\\');
                    $r = strpos($deal_str, '\r');
                    $n = strpos($deal_str, '\n');

                    // echo $deal_str;
                    //   echo '<br/>';


                    if($x_pos == 1 || ( $xiegang_pos == 1 && $r == false && $n == false)){
                      // echo 'jin';
                      //  echo '<br/>';
                      //   print_r($r);
                      //  echo '<br/>';
                      //   print_r($n);
                      //  echo '<br/>';
header('Content-Type: text/html; charset=utf-8');
                       $reg = "/\\\\x.{2}/i";

                        $str = preg_replace_callback($reg,"mdbchar", $deal_str);
                        $oct_array = explode('\\', $str);
                        $filter_array = array();
                        foreach ($oct_array as $key => $value) {
                          if($value && $value !='' && $value > 0){
                            $filter_array[] = base_convert($value,8,16);
                          }
                          
                        }
                        // var_dump($filter_array);
                        $hex = implode('', $filter_array);
                        $str_pack = pack('H*',$hex);
                        $isUTF8 = isUTF8($str_pack);
                        if(!$isUTF8){

                          echo '<br/>';
                          $encode = mb_detect_encoding($str_pack, array('UTF-8','GB2312','GBK'));
                          echo 'encode = '.$encode;
                           echo '<br/>';
                          echo 'bushiutf8='.$deal_str;
                           echo '<br/>';
                            return $deal_str;
                         // $str_pack =   htmlConvertEncode($str_pack);
                         //  echo 'CP936totf8='.$str_pack;
                         //  if(!isUTF8($str_pack)){
                         //    echo 'again_str_pack='.$str_pack;
                         //     echo '<br/>';
                         //  }

                        }

                        // echo '\''.$str_pack.'\'';
                       return '"'.$str_pack.'"';
                     }else{
                      if($x_pos > 1 ){
                         echo $file_path;
                          echo '<br/>';
                         echo $deal_str;
                          echo '<br/>';
                      }



                      // if($r != false || $n != false){
                      //   echo '<br/>';
                      //   echo 'rn';
                      //    echo $deal_str;
                      //     echo '<br/>';
                      // }
                       // echo 'nojin';
                       // echo '<br/>';
                       // echo 'x_pos='.$x_pos;
                       // echo '<br/>';
                       // echo 'xiegang_pos='.$xiegang_pos;
                       // echo '<br/>';
                       // print_r($r);
                       // echo '<br/>';
                       //  print_r($n);
                       // echo '<br/>';

                       return $deal_str;
                     }
                   
                    // echo $str;
                    // exit;
                 // echo $matches[1];
                 // exit;
                // return '\'weiq\'';
                // var_dump($matches);
                // exit;
                // $pattern_tmp = '#(\x)#i';
                // echo preg_replace($pattern_tmp,'%',$matches[0]);
                // exit;
                // foreach ($matches as $key => $value) {
                //    echo $value;
                //    echo '<br/>';
                //    // exit;

                // }
                // exit;
                //$matches[1]返回如：username
                // $name = $matches[1];
                // if (in_array($name, $noMatchs)) {
                //     //$mathches[0]返回如：{end}
                //     return $matches[0];
                // }
                // return array_key_exists($name, $datas) ? $datas[$name] : '';
            }, $content);
  // echo $content;
  // exit;
  return $return_data;
}

 /**
     * 采集的HTML转码
     * 事由：因为采集到非UTF-8的页面会出现中文乱码，又因为会采集不特定的多个网站，只能先判断页面编码后转码
     * @param string $html
     * @param string $charset 如果此值为 true，则返回此HTML的字符集
     * @return null|string|string[]
     */
    function htmlConvertEncode($html, $charset='UTF-8')
    {
        // 检测编码
        $encode = mb_detect_encoding($html, array("ASCII","UTF-8","GB2312","GBK","CP936","BIG5","EUC-CN"));
        // 转码
        if($encode != $charset){
            return mb_convert_encoding($html, 'UTF-8', $encode);
        }
        // 返回字符集
        if($charset === true){
            return $encode;
        }
        return $html;
    }

  /**
     * 将ascii码转为字符串
     * @param type $str  要解码的字符串
     * @param type $prefix  前缀，默认:&#
     * @return type
     */
    function decode($str, $prefix="&#") {
        $str = str_replace($prefix, "", $str);
        $a = explode(";", $str);
        foreach ($a as $dec) {
            if ($dec < 128) {
                $utf .= chr($dec);
            } else if ($dec < 2048) {
                $utf .= chr(192 + (($dec - ($dec % 64)) / 64));
                $utf .= chr(128 + ($dec % 64));
            } else {
                $utf .= chr(224 + (($dec - ($dec % 4096)) / 4096));
                $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
                $utf .= chr(128 + ($dec % 64));
            }
        }
        return $utf;
    }
 
    /**
     * 将字符串转换为ascii码
     * @param type $c 要编码的字符串
     * @param type $prefix  前缀，默认：&#
     * @return string
     */
    function encode($c, $prefix="&#") {
        $len = strlen($c);
        $a = 0;
        while ($a < $len) {
            $ud = 0;
            if (ord($c{$a}) >= 0 && ord($c{$a}) <= 127) {
                $ud = ord($c{$a});
                $a += 1;
            } else if (ord($c{$a}) >= 192 && ord($c{$a}) <= 223) {
                $ud = (ord($c{$a}) - 192) * 64 + (ord($c{$a + 1}) - 128);
                $a += 2;
            } else if (ord($c{$a}) >= 224 && ord($c{$a}) <= 239) {
                $ud = (ord($c{$a}) - 224) * 4096 + (ord($c{$a + 1}) - 128) * 64 + (ord($c{$a + 2}) - 128);
                $a += 3;
            } else if (ord($c{$a}) >= 240 && ord($c{$a}) <= 247) {
                $ud = (ord($c{$a}) - 240) * 262144 + (ord($c{$a + 1}) - 128) * 4096 + (ord($c{$a + 2}) - 128) * 64 + (ord($c{$a + 3}) - 128);
                $a += 4;
            } else if (ord($c{$a}) >= 248 && ord($c{$a}) <= 251) {
                $ud = (ord($c{$a}) - 248) * 16777216 + (ord($c{$a + 1}) - 128) * 262144 + (ord($c{$a + 2}) - 128) * 4096 + (ord($c{$a + 3}) - 128) * 64 + (ord($c{$a + 4}) - 128);
                $a += 5;
            } else if (ord($c{$a}) >= 252 && ord($c{$a}) <= 253) {
                $ud = (ord($c{$a}) - 252) * 1073741824 + (ord($c{$a + 1}) - 128) * 16777216 + (ord($c{$a + 2}) - 128) * 262144 + (ord($c{$a + 3}) - 128) * 4096 + (ord($c{$a + 4}) - 128) * 64 + (ord($c{$a + 5}) - 128);
                $a += 6;
            } else if (ord($c{$a}) >= 254 && ord($c{$a}) <= 255) { //error
                $ud = false;
            }
            $scill .= $prefix.$ud.";";
        }
        return $scill;
    }
function asciitostr($sacii){
        $asc_arr= str_split(strtolower($sacii),2);
        $str='';
        for($i=0;$i<count($asc_arr);$i++){
            $str.=chr(hexdec($asc_arr[$i][1].$asc_arr[$i][0]));
        }
        echo $str;
        exit;
        return mb_convert_encoding($str,'UTF-8','GB2312');
    }
function hex_replace($str){//转换成ASCII
  echo $str;
  exit;
$tmp = substr($str, 0, 1);

if($tmp == 'x' || $tmp == 'X'){ //判断是否是 16 进制, 否则当 8 进制处理
return chr(hexdec($str));
} else {
return chr(octdec($str));
}
}
 //查找16进制并替换为8进制
function deal_hex($str){
    $pattern = '#\x(.*?)#i';
    var_dump($str);
    exit;
  preg_replace_callback($pattern, function ($matches) use ($datas, $noMatchs) {
                
                var_dump($matches);
                exit;
                // $pattern_tmp = '#(\x)#i';
                // echo preg_replace($pattern_tmp,'%',$matches[0]);
                // exit;
                // foreach ($matches as $key => $value) {
                //    echo $value;
                //    echo '<br/>';
                //    // exit;

                // }
                // exit;
                //$matches[1]返回如：username
                // $name = $matches[1];
                // if (in_array($name, $noMatchs)) {
                //     //$mathches[0]返回如：{end}
                //     return $matches[0];
                // }
                // return array_key_exists($name, $datas) ? $datas[$name] : '';
            }, $str);

}

header('Content-Type:text/html; charset=utf-8');
$asscii = "\163\164\x6f\x72\145\x5f\x6e\x61\x6d\145";
$str = $asscii;
$str = preg_replace('/\\\\([xX][\\dA-Fa-f]{1,2})|\\\\([\\d]{1,3})/e', 'hex_replace(\'$1$2\')', $str);//替换
// var_dump($str);
// exit;
// echo $str;
// exit;
// deal_hex($asscii);
// exit;
// echo $asscii;
// exit;
// echo $str;
// exit;
// echo asciitostr($str);
// exit;

header('Content-Type: text/html; charset=utf-8');
read_all('C:\WWWROOT\LocalUser\weiq\www\addons\lywywl_ztb\inc_deal');
// echo  encode("PHP二次开发：www.php2.cc");
// exit;
// echo decode('\163\164\x6f\x72\145\x5f\x6e\x61\x6d\145');

// exit;
 // echo 'count = '.$this->count;
 //     exit;
?>